package com.cloud.salon.client.authority.service.impl;

import com.cloud.salon.client.authority.repository.UserRepository;
import com.cloud.salon.client.authority.service.RoleService;
import com.cloud.salon.client.authority.service.UserService;
import com.cloud.salon.common.crud.service.impl.CRUDServiceImpl;
import com.cloud.salon.common.base.response.Res;
import com.cloud.salon.common.base.entity.authority.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 用户Service实现类
 * @Author wolf--LZH
 * @CreateDate 2019/4/10 0010 下午 1:30
 */
@Service
public class UserServiceImpl extends CRUDServiceImpl<User, UserRepository> implements UserService {

	@Autowired
	private UserRepository repository;
	@Autowired
	private RoleService roleService;

	@Override
	public Res<User> findByUsername(String username) {
		return new Res(0, "获取用户成功", repository.findByUsername(username));
	}

	@Override
	public Res<List<User>> findByRole(Integer roleId) {
		List<User> users = repository.findByRole(roleId);

		if(users != null)
			return new Res(0, "查找成功", users);
		else
			return new Res(-3, "查找失败");
	}

	@Override
	public Res<User> save(User entity) {
		User temp = this.findByUsername(entity.getUsername()).getData();
		if(temp == null) {
			temp = repository.save(entity);
			if(temp != null)
				return new Res(0, "添加成功", temp);
			return  new Res(-3, "添加失败,请稍后再试");
		}
		else
			return new Res(-3, "添加失败,该账号已存在");
	}

	@Override
	public Res<User> update(User entity) {
		//如果不存在该实体，不准更新数据库，并返回null
		User temp = findById(entity.getId()).getData();
		if (temp == null) {
			return new Res(-3, "不存在此实体,请确认后再修改");
		}
		entity.setUsername(temp.getUsername());
		return new Res(0, "修改成功", repository.save(entity));
	}
}
